package com.gframework.antibrush.limiter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 基于redistemplate redis客户端的限流实现.
 * <p>建议采用redisson redis客户端。{@link CurrentLimiterRedisson}
 * 
 * @since 1.0.0
 * @author Ghwolf
 */
@ConditionalOnClass(RedisTemplate.class)
@ConditionalOnSingleCandidate(RedisTemplate.class)
@ConditionalOnMissingBean(CurrentLimiter.class)
public class CurrentLimiterRedisTemplate implements CurrentLimiter{
	
	@Autowired
	private RedisTemplate<? super String,?> redisTemplate ;
	
	@Override
	public boolean rate(LimitRequest anno, String key) {
		long count = redisTemplate.opsForValue().increment(key);
		// XXX 在某些情况下（例如平稳持续不断的均速请求），会导致一段时间内一直无法请求
		if (count > anno.maxRequest()) {
			return false ;
		} else {
			redisTemplate.expire(key, anno.time(),anno.timeUnit());
			return true ;
		}
	}

}
